package com.whz.streamdemo;

import com.google.common.collect.Lists;
import com.google.common.collect.Sets;

import java.util.*;

/**
 * @Author: sinosoft
 * @Description:
 * @Date: Create in 19:24 2021/5/18
 * @Modified By:
 */
public class PowerSet {
    public static final <E> Collection<Set<E>> of(Set<E> s) {
        List<E> src = Lists.newArrayList(s);
        if(src.size() > 30) {
            throw new IllegalArgumentException("Set集合容量过大");
        }
        return new AbstractList<Set<E>>() {
            @Override
            public Set<E> get(int index) {
                Set<E> result = Sets.newHashSet();
                for(int i = 0; index != 0; i++, index >>= 1) {
                    // index & 1用来判断奇偶 == 1 index是奇数
                    // index & 1 == 0 index是偶数
                    if((index & 1) == 1) {
                        result.add(src.get(i));
                    }
                }
                return result;
            }

            @Override
            public int size() {
                return 1 << src.size();
            }

            @Override
            public boolean contains(Object o) {
                return o instanceof Set && src.containsAll((Set)o);
            }
        };
    }
}
